const express = require("express");
const router = express.Router();

const md5 = require("md5"); // 数据加密算法
const UserModel = require("../mongodb/models/User");

const LOGIN_ERROR = "用户登录失败";
const LOGIN_WRONG = "昵称密码错误";

router.get("/login", (req, res) => {
    res.render("login");
}); // 用户登录注册模板
router.post("/login", (req, res) => {
    let { username, password } = req.body;
    password = md5(password); // 密码数据加密
    UserModel.findOne({ username }, (error, find) => {
        if (error) {
            console.log(error);
            res.status(500).send(LOGIN_ERROR);
            return;
        }
        if (!find) {
            // 新用户
            UserModel.create({
                username, password
            }, (error, user) => {
                if (error) {
                    console.log(error);
                    res.status(500).send(LOGIN_ERROR);
                    return;
                }
                console.log(user);
                req.session.userid = user._id;
                req.session.username = user.username;
                res.redirect("/accounts"); // 用户注册成功，跳转到列表页
            });
        } else {
            // 老用户
            console.log(find);
            if (find.password === password) {
                req.session.userid = find._id;
                req.session.username = find.username;
                res.redirect("/accounts"); // 用户登录成功，跳转到列表页
            } else { res.status(500).send(LOGIN_WRONG); }
        }
    });
}); // 用户登录注册操作
router.post("/logout", (req, res) => {
    req.session.destroy(() => { res.redirect("/login"); });
}); // 用户退出操作(销毁用户登录信息，跳转回登录注册页)
module.exports = router;
